<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/11/8
 * Time: 18:29
 */

namespace console\controllers\integrate;

use business\base\caches\DataCache;
use business\company\models\SupplierBasicModel;
use business\company\repositories\SupplierRepository;
use business\company\services\queues\SupplierProducerService;
use business\company\services\SupplierService;
use business\base\services\SupplierTagsService;
use common\cache\CacheManager;
use yii\console\Controller;

class SupplierTagsController extends Controller
{
    /**
     * 每次查询取出的最大数量
     * @var int
     */
    const MAX_COUNT_PER_QUERY = 100;

    /**
     * 定义执行脚本时yii的路径
     * @return string
     */
    protected function getYii()
    {
        return dirname(dirname(dirname(__DIR__))) . '/yii';
    }

    /**
     * 初始化同步标签库
     * php yii integrate/supplier-tags/rsync
     */
    public function actionRsync($type = 'full')
    {
        // 执行脚本
        $runs = [
            'full' => ['rsync-supplier-tags', 'rsync-industry-top', 'rsync-famous-list', 'rsync-strategy-info'],
            'increment' => ['rsync-supplier-tags']
        ];
        $actions = $runs[$type];
        if (!empty($actions)) {
            foreach ($actions as $action) {
                $cmd = sprintf("php %s integrate/supplier-tags/%s '%s'", $this->getYii(), $action, $type);
                print "正在执行:{$cmd}\n";
                $output = system($cmd);
                print "{$output}\n";
            }
        }
    }

    /**
     * 更新供应商标签库（针对于战略合作、签约金额标签清洗）
     * php yii integrate/supplier-tags/update
     */
    public function actionUpdate()
    {
        try {
//            ini_set("display_errors","On");
//            error_reporting(E_ALL);
            echo '开始时间' . microtime() . PHP_EOL;
            $sql = <<<sql
            SELECT supplier_id, supplier_name, tag_type FROM `dotnet_operation`.`sc_supplier_tags` /*WHERE supplier_id = 'G138313'*/
sql;
            $connection = \Yii::$app->get('db');
            $suppliers = $connection->createCommand($sql)->queryAll();
            $supplierProducerService = new SupplierProducerService();
            if (!empty($suppliers)) {
                foreach ($suppliers as $supplier) {
                    $supplierId = $supplier['supplier_id'];
                    $supplierName = $supplier['supplier_name'];
                    $tagType = $supplier['tag_type'];

                    if (!empty($tagType)) {
                        $tagTypes = explode(',', strval($tagType));
                    }

                    // 签约金额
                    $sql = <<<sql
                        SELECT `uid` FROM `dotnet_operation`.`sc_supplier_tag_contracted_amount` WHERE `supplier_id` = '$supplierId' AND `is_deleted` = 0
sql;
                    /** @var Connection $connection */
                    $connection = \Yii::$app->get('db');
                    $result = $connection->createCommand($sql)->queryOne();

                    if (!empty($result)) {
                        !in_array(4, $tagTypes) && array_push($tagTypes, 4);
                    }

                    // 战略合作
                    $sql = <<<sql
                        SELECT `uid` FROM `b2b_data_center`.`youcai_hundred_supplier_data` WHERE (`supplier_id` = '$supplierId' OR `supplier_name` = '$supplierName') AND `is_audit` = 1
sql;
                    /** @var Connection $connection */
                    $connection = \Yii::$app->get('db');
                    $result = $connection->createCommand($sql)->queryOne();

                    if (!empty($result)) {
                        !in_array(3, $tagTypes) && array_push($tagTypes, 3);
                    }

                    $tagTypes = !empty($tagTypes) ? implode(',', $tagTypes) : '';

                    if (!empty($tagTypes)) {
                        echo $supplierId . ' ' . $tagTypes . PHP_EOL;
                        $sql = <<<sql
                        UPDATE `dotnet_operation`.`sc_supplier_tags` SET `tag_type` = '$tagTypes' WHERE `supplier_id` = '$supplierId' AND `is_deleted` = 0
sql;
                        \Yii::$app->db->createCommand($sql)->execute();
                        $supplierProducerService->single($supplierId);
                    }

                    $tagTypes = [];
                }
            }
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据更新出错，错误信息：'.$ex->getMessage();
        }
    }

    /**
     * 初始化同步供应商信息到标签库
     * php yii integrate/supplier-tags/rsync-supplier-tags
     */
    public function actionRsyncSupplierTags($type = 'full')
    {
        try {
            echo '开始时间' . microtime() . PHP_EOL;
            $supplierService = new SupplierService();
            switch ($type) {
                // 全量同步
                case 'full' :
                    $supplierIds = $supplierService->getSupplierIdsList();
                    if (empty($supplierIds)) {
                        echo '没有找到供应商';
                        return;
                    }
                    break;
                // 增量同步
                case 'increment' :
                    $dataCache = new DataCache();
                    $supplierRepository = new SupplierRepository();
                    $lastQueryTime = 'Last-Supplier-Tags-Query-Time';
                    // 返回上一次查询时间
                    list($startDate, $endDate) = $dataCache->getLastSearchTime($lastQueryTime, 2);
                    $totalCount = $supplierRepository->getSupplierCountByTimeSlot($startDate, $endDate);
                    $loopCount = ceil($totalCount / self::MAX_COUNT_PER_QUERY);
                    $lastSupplierId = "0";
                    $supplierIds = [];
                    for ($i = 0; $i < $loopCount; $i++) {
                        $changedSupplierIds = $supplierRepository->getChangedSupplierInfoByTimeSlot($startDate, $endDate,
                            $lastSupplierId, self::MAX_COUNT_PER_QUERY);
                        $supplierIds = array_merge($supplierIds, $changedSupplierIds);
                        if (empty($changedSupplierIds)) {
                            continue;
                        }
                        $lastSupplierId = $changedSupplierIds[count($changedSupplierIds) - 1];
                    }
                    break;
                default :
                    throw new \Exception("无效的同步类型" . PHP_EOL);
            }
            (new SupplierTagsService())->rsyncSupplierTags($supplierIds);
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据同步出错，错误信息：'.$ex->getMessage();
        }
    }

    /**
     * 初始化同步行业Top级数据（只同步一次）
     * php yii integrate/supplier-tags/rsync-industry-top
     * @return null
     */
    public function actionRsyncIndustryTop()
    {
        try {
            echo '开始时间' . microtime() . PHP_EOL;
            (new SupplierTagsService())->rsyncIndustryTop();
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据同步出错，错误信息：'.$ex->getMessage();
        }
    }

    /**
     * 初始化同步榜上有名数据（只同步一次）
     * php yii integrate/supplier-tags/rsync-famous-list
     * @return null
     */
    public function actionRsyncFamousList()
    {
        try {
            echo '开始时间' . microtime() . PHP_EOL;
            (new SupplierTagsService())->rsyncFamousList();
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据同步出错，错误信息：'.$ex->getMessage();
        }
    }

    /**
     * 初始化同步战略合作数据（只同步一次，增量同步根据后期战略合作业务表字段来进行调整）
     * php yii integrate/supplier-tags/rsync-strategy-info
     * @return null
     */
    public function actionRsyncStrategyInfo($type = 'full')
    {
        try {
            echo '开始时间' . microtime() . PHP_EOL;
            $supplierTagsService = new SupplierTagsService();
            $lastIdKey = 'Last-Strategy-Info-Id-Time';
            $lastSupplierId = '0';
            switch ($type) {
                // 全量同步
                case 'full' :
                    $ids = $supplierTagsService->getHundredSupplierIdsList($lastSupplierId);
                    $lastSupplierId = $ids[count($ids) - 1];
                    break;
                // 增量同步
                case 'increment' :
                    $lastSupplierId = CacheManager::get($lastIdKey);
                    if (!empty($lastSupplierId)) {
                        $ids = $supplierTagsService->getHundredSupplierIdsList($lastSupplierId);
                        $lastSupplierId = $ids[count($ids) - 1];
                    }
                    break;
                default :
                    throw new \Exception("无效的同步类型" . PHP_EOL);
            }
//            CacheManager::set($lastIdKey, $lastSupplierId);
            (new SupplierTagsService())->rsyncStrategyInfo($ids);
            echo '结束时间' . microtime()  . PHP_EOL;
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            echo '数据同步出错，错误信息：'.$ex->getMessage();
        }
    }
}
